package com.zxn.time

import java.util.*

/**
 * Created by zxn on 2022/1/28.
 */

/**
 * 计算给定日期距离当前时间相差的天数.
 */
fun separatedDays(date: String, @PatternType pattern: String): Int {

    val dateCalendar = Calendar.getInstance()
    dateCalendar.time = Date(timeToStamp(date, pattern))

    val currCalendar = Calendar.getInstance()

    val oldDay = dateCalendar[Calendar.DAY_OF_YEAR]
    val currDay = currCalendar[Calendar.DAY_OF_YEAR]

    val oldYear = dateCalendar[Calendar.YEAR]
    val currYear = currCalendar[Calendar.YEAR]
    return -(if (oldYear != currYear) { //不同一年
        var timeDistance = 0
        for (i in oldYear until currYear) {
            timeDistance += if (i % 4 == 0 && i % 100 != 0 || i % 400 == 0) {    //闰年
                366
            } else {  //不是闰年
                365
            }
        }
        timeDistance + (currDay - oldDay)
    } else { //同年
        currDay - oldDay
    })

}